package com.couldsail.takeaway.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.couldsail.takeaway.constant.MessageConstant;
import com.couldsail.takeaway.constant.UserConstant;
import com.couldsail.takeaway.context.BaseContext;
import com.couldsail.takeaway.execption.DeletionNotAllowedException;
import com.couldsail.takeaway.mapper.UserMapper;
import com.couldsail.takeaway.pojo.dto.UserLoginDTO;
import com.couldsail.takeaway.pojo.dto.UserUpdateDTO;
import com.couldsail.takeaway.pojo.entity.User;
import com.couldsail.takeaway.pojo.vo.UserVO;
import com.couldsail.takeaway.properties.WeChatProperties;
import com.couldsail.takeaway.service.UserService;
import com.couldsail.takeaway.utils.HttpClientUtil;
import com.couldsail.takeaway.utils.UniqueIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class UserSerivceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final UserMapper userMapper;
    private final WeChatProperties weChatProperties;
    public User wxLogin(UserLoginDTO userLoginDTO) throws IOException, CloneNotSupportedException {
        // 调用微信服务获取到用户的openid
        String openid = getOpenid(userLoginDTO.getCode());

        // 检查 openid 是否为空或无效
        if (openid == null || openid.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.LOGIN_FAILED);
        }

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser == null) {
            // 是新用户，插入数据并回显 id
            User newUser = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .name("用户"+UniqueIdGenerator.generateUniqueId())
                    .avatar(UserConstant.DEFAULT_AVATAR)
                    .sex(UserConstant.DEFAULT_SEX)
                    .id(UniqueIdGenerator.generateUniqueId())
                    .build();

            // 插入新用户并获取生成的 ID
            userMapper.insert(newUser);
            return newUser;
        } else {
            // 返回现有用户信息
            return existingUser;
        }
    }
    /**
     * 获取用户信息
     */
    @Override
    public UserVO getDetail() {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userMapper.selectById(BaseContext.getCurrentId()),userVO);
        return userVO;
    }
    /**
     * 修改用户信息
     */
    @Override
    public void updateDetail(UserUpdateDTO userUpdateDTO) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        user.setId(BaseContext.getCurrentId());
        userMapper.updateById(user);
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        System.out.println(openid);
        return openid;
    }

}
